import ast

import requests

import pandas as pd
import base64
import json
import os
import shutil
import time
import random
from collections import OrderedDict
from urllib.parse import quote_plus
import redis
import requests
from sqlalchemy import create_engine
from DrissionPage import ChromiumPage
from DrissionPage import ChromiumOptions
from DrissionPage.common import Settings
from DrissionPage.common import Keys
from DrissionPage.common import Actions
import pymysql
from DrissionPage.errors import *

import datetime

"""
https://customer.xiaohongshu.com/api/cas/customer/web/qr-code?service=https:%2F%2Fcreator.xiaohongshu.com&qr_code_id=68c517395516719772176435"""


class DOUYIN_LIFE:
    def __init__(self, user_id,account_id,order_id):
        self.CO = ChromiumOptions()  ##创建chrome实例
        # self.user_id = self.user_input()  ##用户
        self.user_id = str(user_id)  ##用户
        self.account_id = account_id
        self.order_id = order_id
        self.PORT = self.port_input()  ##chrome端口
        self.CO.set_paths(
            browser_path="browser_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")  ##chrome启动路径
        self.CO.set_local_port(self.PORT)  ##生成的端口 这里是手动生成
        self.CO.set_user_data_path(os.getcwd() + '/user_info_dir/{}'.format(self.user_id))  ##用户chrome文件夹
        # self.CO.arguments.append('--headless')
        self.ch = ChromiumPage(self.CO)

        self.ch.set.window.max()  ##chrome窗口最大化
        self.ac = Actions(self.ch)
        # self.fans = self.xhs_user_info_requests()
        # print(self.user_id)
        # self.redis_conn = redis.StrictRedis(host='r-bp162522qrwjh5e7jhpd.redis.rds.aliyuncs.com', port=6379,
        #                                     password='123sdmmh568%$#vs*!', db=21)
        self.redis_conn = redis.StrictRedis(host='r-bp1y4wxs1fa8vxd1xspd.redis.rds.aliyuncs.com', port=6379,
                                            password='Jison0820', db=0)

    """根据用户ID查出端口号"""

    def port_fe(self):
        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center where spider_user_id='{}'".format(
            self.user_id)
        spider_config = self.pymysql_fetchall(sql)
        port = []
        for i in spider_config:
            port.append(i[1])

        return ''.join(port)

    """自动输入端口号"""

    def port_input(self):

        port1 = random.randint(5000, 9000)

        cc = self.port_jiance()
        while True:
            cc = self.port_jiance()
            if cc == "用户存在":
                # print("当前用户存在")
                port_ = self.port_fe()
                # print(port_)
                return port_
            if cc == "端口不存在":
                # print(port1)
                return port1
            else:
                return self.PORT

    """自动随机生成端口 并进行检测"""

    def port_jiance(self):
        port1 = random.randint(5000, 9000)

        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center"
        spider_config = self.pymysql_fetchall(sql)
        port_list = []
        # print(spider_config)
        for i in spider_config:
            port_list.append(i[1])
        user_exists = self.user_state()
        # print(user_exists, '************')
        if user_exists == "用户不存在":
            if port1 not in port_list:
                return "端口不存在"
            else:
                return "端口存在"
        else:
            return '用户存在'

    """查询数据库"""

    def pymysql_fetchall(self, sql):

        con = pymysql.connect(host='rm-bp1be6s3581xp13rfco.mysql.rds.aliyuncs.com', port=3306, user='root',
                              passwd='Jison0820', db='data-warehouse', charset='utf8')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql)
        sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return sql_result

    """从数据库判断用户是否存在"""

    def user_state(self):
        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center"
        result = self.pymysql_fetchall(sql)
        user_list = []
        for i in result:
            user_list.append(i[0])
        # print(user_list)
        if self.user_id in user_list:
            # print("存在")
            return "用户存在"
        else:
            return "用户不存在"

    """判断用户是否在数据库中 不在为新用户 在的话为老用户"""

    def user_info(self):
        engine2 = self.mysql_config()
        data_frame = pd.DataFrame([{"spider_user_id": str(self.user_id), "spider_port": str(self.PORT)}])
        # print(data_frame)
        # pd.io.sql.to_sql(data_frame, 'xhs_user_info', engine2, schema='live_data',if_exists='append',index=False)
        return data_frame

    # def mysql_config(self):
    #     user = 'live_data'
    #     password = quote_plus('CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ')
    #     # passwd ='merchantsasd123!@%&'
    #     host = 'rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com'
    #     # port1 ='3306'
    #     dbname2 = 'live_data'
    #     engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
    #     return engine2

    def mysql_config(self):
        user = 'root'
        password = quote_plus('Jison0820')
        # passwd ='merchantsasd123!@%&'
        host = 'rm-bp1be6s3581xp13rfco.mysql.rds.aliyuncs.com'
        # port1 ='3306'
        dbname2 = 'data-warehouse'
        engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
        return engine2

    """修改用户登录状态的mysql"""

    def pymysql_update(self, sql, num):

        con = pymysql.connect(host='rm-bp1be6s3581xp13rfco.mysql.rds.aliyuncs.com', port=3306, user='root',
                              passwd='Jison0820', db='data-warehouse', charset='utf8')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql, (num, self.user_id))
        # sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return "用户{}状态修改成功,当前状态值为{}".format(self.user_id, num)

    """修改用户三十天数据"""

    def pymysql_update_total(self, sql):

        con = pymysql.connect(host='rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com', port=3306, user='root',
                              passwd='CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ', db='data-warehouse', charset='utf8mb4')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql, )
        # sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return "用户{}值成功,当前状态值".format(self.user_id)

    """获取cookies"""

    def get_cookies(self):
        cookies_str = ''
        for i in self.ch.cookies(all_domains=False, all_info=True):
            my_ordered_dict = OrderedDict(i)

            # 取出前两个键值对
            first_two_items = list(my_ordered_dict.items())[:2]
            key_value_str = ''
            count_key_value = 0
            for i in first_two_items:
                count_key_value = count_key_value + 1
                if count_key_value == 1:
                    key_value_str = key_value_str + i[1] + '='
                else:
                    key_value_str = key_value_str + i[1]
            cookies_str = cookies_str + key_value_str + ";"
        return cookies_str

    def listen_shop_name_list(self):
        self.ch.refresh()
        self.ch.listen.start(
            'https://life.douyin.com/life/gate/v1/account/groupAccountList/?page_index=1&page_size=20&name=')

        shop_name_index = []
        life_account_id_list = []
        shop_name = '上海明牌首饰有限公司'
        for packet in self.ch.listen.steps(timeout=3):
            account_list = packet.response.body["data"]["list"]
            life_account_id = account_list[0]["detail"]["life_account_id"]
            life_account_id_list.append(life_account_id)
            # 使用 enumerate 遍历列表并查找索引
            for index, item in enumerate(account_list):
                if item['account_name'] == shop_name:
                    shop_name_index.append(index)
                    break  # 找到后退出循环
            else:
                print("未找到")  # 如果没有找到，则输出未找

        shop_name_index = shop_name_index[0] + 1

        ##选择账号下的店铺名称
        self.ch.ele(
            'xpath://*[@id="life_login_page"]/div[2]/div/div/div/div[2]/div/div[1]/div/div/div/div[{}]/div/div/div'.format(
                shop_name_index)).click()
        time.sleep(0.5)

        self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div[2]/div/div[2]/button').click()

        return life_account_id_list[0]

    # def listen_shop_name_list_id(self):
    #     self.ch.refresh()
    #     # time.sleep(5)
    #
    #     self.ch.listen.start('https://life.douyin.com/life/gate/v1/account/groupAccountList/')
    #
    #     shop_name_index = []
    #
    #     life_account_id_list = []
    #     shop_name = self.shop_name
    #     for packet in self.ch.listen.steps(timeout=30):
    #         account_list = packet.response.body["data"]["list"]
    #         print(account_list,"********账号名称列表********")
    #         for i in account_list:
    #             print(i,"********")
    #             if shop_name == i["account_name"]:
    #                 print(i)
    #                 life_account_id_list.append(i["detail"]["life_account_id"])
    #         # print(life_account_id_list[0])
    #     return life_account_id_list[0]



    def select_order_refer(self):
        time.sleep(3)
        cookies = self.get_cookies()
        headers = {"Cookie": cookies,
                   "referer": "https://life.douyin.com/p/liteapp/fulfillment-fusion/order?groupid=1765480014223375"}
        order_json_list = []
        for order in self.order_id:
            print("订单ID",order)
            payload = {
                "filter": {
                    # "start_time": 1728576000,
                    # "end_time": 1729180799,
                    "product_option": [],
                    "order_id": order,
                    "is_market": False,
                    "is_market_poi": False,

                },
                "is_user_poi_filter": False,
                "industry": "industry_common",
                "permission_common_param": {}
            }
            url = 'https://life.douyin.com/life/trade_view/v1/sale/query/certificate_list/?page_index=1&page_size=20&industry=industry_common&root_life_account_id=%s' % self.account_id
            time.sleep(0.5)
            amount = requests.post(url, headers=headers, data=json.dumps(payload))
            amount_order = amount.json()["data"]["list"][0]
            # 订单编号
            order_id = amount_order["order_id"]
            # 订单状态{Status:1未核销 status:2已核销 status:4已退款}
            order_status = amount_order["status"]
            # 订单标签
            order_tag_name = amount_order["order_tag"][0]["tag_name"]
            ##订单标签类型
            order_tag_type = amount_order["order_tag"][0]["tag_type"]
            # 商品名称
            order_title = amount_order["sku"]["title"]
            # 商品图片
            order_image = amount_order["sku"]["image"]
            ##sku ID
            order_sku_id = amount_order["sku"]["sku_id"]
            ##支付时间
            order_pay_time = amount_order["pay_time"]
            ##商品原价
            crossed_amount = amount_order["amount"]["crossed_amount"]
            crossed_amount = float(crossed_amount) / 100

            ##售卖金额
            coupon_pay_amount = amount_order["amount"]['coupon_pay_amount']
            coupon_pay_amount = float(coupon_pay_amount) / 100

            ##订单实收金额
            pay_amount = amount_order["amount"]['pay_amount']
            pay_amount = float(pay_amount) / 100

            ##成交渠道
            sale_channel = amount_order["extra"]["attribute"]["sale_channel"]

            sale_user_nickname = amount_order["extra"]["attribute"]["sale_user_nickname"]

            video_share_url = amount_order["extra"]["attribute"]["video_share_url"]
            print(video_share_url)
            if 'share/video' in video_share_url:
                video_share_id = video_share_url.split('https://www.iesdouyin.com/share/video/')[1]
                print(video_share_id)
            if 'webcast/reflow/' in video_share_url:
                video_share_id = video_share_url.split('https://webcast.amemv.com/webcast/reflow/')[1]
                print(video_share_id)
            if '//user/profile/' in video_share_url:
                print("存在")
                video_share_id = video_share_url.split('//user/profile/')[1]
                print(video_share_id)

            if video_share_url == '':
                video_share_id = ''

            # 带货角色
            sale_user_role = amount_order["extra"]["attribute"]["sale_user_role"]

            order_json = {"random":self.user_id,"account_id":self.account_id,"order_id": order_id, "order_status": order_status, "title": order_title, "image": order_image,
                          "sku_id": order_sku_id, "pay_time": order_pay_time,
                          "crossed_amount": crossed_amount, "coupon_pay_amount": coupon_pay_amount,
                          "pay_amount": pay_amount, "order_tag_name": order_tag_name, "order_tag_type": order_tag_type,
                          "sale_channel": sale_channel, "sale_user_role": sale_user_role,
                          "sale_user_nickname": sale_user_nickname, "video_share_id": video_share_id}
            print(order_json)
            order_json_list.append(order_json)

        data_order_frame = pd.DataFrame(order_json_list)
        pd.io.sql.to_sql(data_order_frame, 'dy_life_order_data', self.mysql_config(), schema='data-warehouse',
                         if_exists='append', index=False)

        return order_json_list


    """用户不存在时，删除生成的指定的用户文件夹"""

    def delete_folder_random(self,random_id):
        try:
            shutil.rmtree(os.getcwd() + "\\user_info_dir\\" + random_id)
            print(f"成功删除文件夹")
        except OSError as e:
            print(f"删除文件夹失败")

    def dy_creator_center_spider(self):

        print('用户:', self.user_id, '此次的端口是:', self.PORT)
        data = pd.read_sql("select * from dy_life_center where spider_user_id='{}'".format(self.user_id),self.mysql_config())
        if data.empty:
            self.ch.close()
            """删除指定的不存在的用户文件夹"""
            self.delete_folder_random(self.user_id)
            return {"code":500,"msg":"该用户不存在或未授权"}
        else:
            self.ch.get('https://life.douyin.com/p/login')
            time.sleep(2)
            # user_it_exist = self.user_state()
            # data_frame = self.user_info()
            # if user_it_exist == "用户不存在":
            #     data_frame["spider_login_code"] = '0'
            #     pd.io.sql.to_sql(data_frame, 'dy_life_center', self.mysql_config(), schema='data-warehouse',
            #                      if_exists='append', index=False)

            login_url_is = self.ch.url
            if login_url_is == "https://life.douyin.com/p/login":
                # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[1]/div/span/span[2]/label').input('18868750739\n')
                # time.sleep(0.5)

                time.sleep(60)
                # ###获取验证码
                # time.sleep(2)
                # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[2]/div/span/label/span/span').click()
                #
                # time.sleep(5)

            # self.select_order_refer()
            time.sleep(3)
            # douyin_life_id = self.listen_shop_name_list_id()
            # print(douyin_life_id)
            orderr_json = self.select_order_refer()
            print(orderr_json)
            self.ch.close()
            return orderr_json

# def main_result_dy_life():
#     dy_center = DOUYIN_LIFE(user_id='js_test_account_3',shop_name)
#     aa = dy_center.dy_creator_center_spider()


# dy_center = DOUYIN_LIFE(user_id='js_test_account_3',shop_name='上海明牌首饰有限公司',order_id=["1072489256283543788","1072500267659864304"])
# aa = dy_center.dy_creator_center_spider()

